package com.sun.order.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.sun.commons.pojo.TbItemVO;
import com.sun.commons.pojo.UserByToken;
import com.sun.commons.utils.CookieUtils;
import com.sun.commons.utils.HttpClientUtil;
import com.sun.commons.utils.IDUtils;
import com.sun.commons.utils.JsonUtils;
import com.sun.commons.utils.Tools;
import com.sun.dubbo.webmanage.service.TbItemDubboService;
import com.sun.dubbo.webmanage.service.TbOrderDubboService;
import com.sun.dubbo.webmanage.service.TbOrderItemDubboService;
import com.sun.dubbo.webmanage.service.TbOrderShippingDubboService;
import com.sun.order.pojo.CreateOrderVO;
import com.sun.redis.dao.RedisDao;
import com.sun.webmanage.model.TbItem;
import com.sun.webmanage.model.TbOrder;
import com.sun.webmanage.model.TbOrderItem;
import com.sun.webmanage.model.TbOrderShipping;
import com.sun.webmanage.model.TbUser;

@Service("OrderService")
public class OrderServiceImpl implements OrderService {

	@Resource
	private RedisDao redisDao;
	@Resource
	private CommonConfig commonConfig;
	@Reference
	private TbItemDubboService tbItemDubboService;
	@Reference
	private TbOrderDubboService tbOrderDubboService;
	@Reference
	private TbOrderItemDubboService tbOrderItemDubboService;
	@Reference
	private TbOrderShippingDubboService tbOrderShippingDubboService;

	@Value("${cart.cache.item}")
	private String catRedisKey;

	private TbUser getUserInfo(HttpServletRequest request) {
		String token = CookieUtils.getCookieValue(request, commonConfig.cookie_token);
		String result = HttpClientUtil.doGet(commonConfig.passport_usertoken_href + token);
		UserByToken userToken = JsonUtils.jsonToPojo(result, UserByToken.class);
		return userToken.getData();
	}

	@Override
	public List<TbItemVO> catList(HttpServletRequest request, Long[] id_array) {
		TbUser userInfo = getUserInfo(request);
		String catListJson = redisDao.getKey(catRedisKey + userInfo.getId());
		List<TbItemVO> cartList = JsonUtils.jsonToList(catListJson, TbItemVO.class);
		List<TbItemVO> retList = new ArrayList<>();
		for (TbItemVO tbItem : cartList) {
			if (Tools.indexOf(id_array, tbItem.getId())) {
				TbItem entry = tbItemDubboService.selectTbItemByPK(tbItem.getId());
				if (entry.getNum() >= tbItem.getNum()) {
					tbItem.setEnough(true);// 有货
				} else {
					tbItem.setEnough(false);
				}
				String image = tbItem.getImage();
				String[] image_array = image == null ? new String[1] : image.split(",");
				tbItem.setImages(image_array);
				retList.add(tbItem);
			}
		}
		return retList;
	}

	@Override
	public boolean createOrder(HttpServletRequest request, CreateOrderVO createOrderVO) throws Exception {
		TbUser userInfo = getUserInfo(request);
		final Date now = new Date();
		TbOrder tbOrder = new TbOrder();
		tbOrder.setOrderId(String.valueOf(IDUtils.getOrderId()));
		tbOrder.setPayment(createOrderVO.getPayment());
		tbOrder.setPaymentType(2);// 支付类型，1、在线支付，2、货到付款
		tbOrder.setPostFee("0.00");
		tbOrder.setStatus(2);// 状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭
		tbOrder.setCreateTime(now);
		tbOrder.setUpdateTime(now);
		tbOrder.setPaymentTime(now);
		tbOrder.setUserId(userInfo.getId());
		tbOrder.setBuyerNick(userInfo.getUsername());
		tbOrder.setShippingName("易购自营物流");
		tbOrder.setShippingCode("0000-0000-0000-0000");
		tbOrder.setBuyerRate(0);
		createOrderVO.setTbOrder(tbOrder);
		if (!tbOrderDubboService.insertTbOrder(tbOrder)) {
			return false;
		}

		String catJson = redisDao.getKey(catRedisKey + userInfo.getId());
		List<TbItemVO> catList = JsonUtils.jsonToList(catJson, TbItemVO.class);

		List<TbOrderItem> orderItem = createOrderVO.getOrderItems();
		for (final TbOrderItem orderitem : orderItem) {
			orderitem.setOrderId(tbOrder.getOrderId());
			orderitem.setId(String.valueOf(IDUtils.getOrderItemId()));
			Iterator<TbItemVO> iter = catList.iterator();
			while (iter.hasNext()) {
				final TbItemVO tbitem = iter.next();
				if (orderitem.getItemId().equals(tbitem.getId().toString())) {
					tbitem.setNum(tbitem.getNum() - orderitem.getNum());
					if (tbitem.getNum() <= 0) {
						iter.remove();
					}

					new Thread() {
						public void run() {
							// 更新商品库存信息
							TbItem tbitemDao = tbItemDubboService.selectTbItemByPK(tbitem.getId());
							tbitemDao.setNum(tbitemDao.getNum() - orderitem.getNum());
							tbitemDao.setUpdated(now);
							tbItemDubboService.updateItem(tbitemDao);
						};
					}.start();

				}
			}
			if (!tbOrderItemDubboService.insertTbOrderItem(orderitem)) {
				return false;
			}
		}

		redisDao.setKey(catRedisKey + userInfo.getId(), JsonUtils.objectToJson(catList));
		TbOrderShipping orderShipping = createOrderVO.getOrderShipping();
		orderShipping.setOrderId(tbOrder.getOrderId());
		orderShipping.setCreated(now);
		orderShipping.setUpdated(now);

		if (!tbOrderShippingDubboService.insertTbOrderShipping(orderShipping)) {
			return false;
		}

		return true;
	}
}
